<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity {

    public $_id;
    public $loginType = 'Front';

    public function authenticate() {
        if ($this->loginType == 'Front') {
            $user = User::model()->find('email=:email', array(':email' => $this->username));
            if (!$user) {
                $this->errorCode = self::ERROR_USERNAME_INVALID;
            } elseif ($user->password !== md5($this->password)) {
                $this->errorCode = self::ERROR_PASSWORD_INVALID;
            } else {
                $this->_id = $user->id;
                $auth = Yii::app()->authManager;
                if (!$auth->isAssigned($user->role, $this->_id)) {
                    if ($auth->assign($user->role, $this->_id)) {
                        Yii::app()->authManager->save();
                    }
                }
                $this->errorCode = self::ERROR_NONE;
                $this->setState('name', $user->fullname);
            }
        }
        if ($this->loginType == 'Back') {
            $user = User::model()->find('email=:email', array(':email' => $this->username));
            if (!$user) {
                $this->errorCode = self::ERROR_USERNAME_INVALID;
            } elseif ($user->password !== md5($this->password)) {
                $this->errorCode = self::ERROR_PASSWORD_INVALID;
            } else {
                $this->_id = $user->id;
                $auth = Yii::app()->authManager;
                if (!$auth->isAssigned($user->role, $this->_id)) {
                    if ($auth->assign($user->role, $this->_id)) {
                        Yii::app()->authManager->save();
                    }
                }
                $this->errorCode = self::ERROR_NONE;
                $this->setState('name', $user->fullname);
            }
        }
        return !$this->errorCode;
    }

    public function getId() {
        return $this->_id;
    }

}
